﻿/*====================================================================================
 * 类名：BasePage
 * 功能描述：站点页面基类
 * 创建者：阴丽宁
 * 创建时间：2010.03.23
 * 修改履历：
 *    1.创建-阴丽宁
 *==================================================================================*/

#region using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
//using PKURG.CostSplit.Entities;
using System.Xml;
using System.Configuration;

//using PKURG.CostSplit.Data;
using Pkurg.PWorld.Entities;
using Pkurg.PWorld.Data;

#endregion                            

/// <summary>
/// 页面的基本方法
/// </summary>
public interface IPageBaseController
{
    /// <summary>
    /// 绑定数据
    /// </summary>
    /// <returns>是否成功</returns>
    bool BindingData();

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns>是否成功</returns>
    bool Save();
}

/// <summary>
/// 页面基类
/// </summary>
public class BasePage : System.Web.UI.Page, IPageBaseController
{
    public BasePage()
    {
        //ValPage();
        this.Load += new EventHandler(this.BasePage_Load);
    }

    public IPageBaseController BaseController
    {
        get { return this as IPageBaseController; }
    }

    #region IPageBaseController 成员

    /// <summary>
    /// 绑定数据
    /// </summary>
    /// <returns>是否成功</returns>
    public virtual bool BindingData()
    {
        return true;
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns>是否成功</returns>
    public virtual bool Save()
    {
        return true;
    }

    #endregion

    #region 登陆用户信息、获得登录用户实体

    public Employee AgentEmployee
    {
        get
        {
            if (Session["AgentEmployee"] == null) Session["AgentEmployee"] = CurrentEmployee;
            return Session["AgentEmployee"] as Employee;
        }
        set { Session["AgentEmployee"] = value; }
    }

    /// <summary>
    /// 登陆用户
    /// </summary>
    public Employee CurrentEmployee
    {
        get
        {            
            return Session["CurrentEmployee"] as Employee;
        }
    }

    public void SetLoginModel(Employee ep)
    {
        Session["CurrentEmployee"] = ep;
    }

    /// <summary>
    /// 获得登录用户实体
    /// </summary>
    /// <returns></returns>
    public void SetLoginModel(DataRow dr)
    {
        Employee user = new Employee();
        user.EmployeeCode = dr["EmployeeCode"].ToString();
        user.EmployeeName = dr["EmployeeName"].ToString();
        user.CompanyCode = dr["CompanyCode"].ToString();
        user.CompanyName = dr["CompanyName"].ToString();
        user.OrgCode = dr["OrgCode"].ToString();
        user.OrgName = dr["OrgName"].ToString();
        user.DepartCode = dr["DepartCode"].ToString();
        user.DepartName = dr["DepartName"].ToString();
        user.CostCenterCode = dr["CostCenterCode"].ToString();
        user.PayrollTo = dr["PayrollTo"].ToString();
        user.EmployeeType = dr["EmployeeType"].ToString();
        user.JobCode = dr["JobCode"].ToString();
        user.JobName = dr["JobName"].ToString();
        user.Email = dr["Email"].ToString();
        user.Remark = dr["Remark"].ToString();
       
        if (!string.IsNullOrEmpty(dr["Gender"].ToString()))
            user.Gender = int.Parse(dr["Gender"].ToString());

        if (!string.IsNullOrEmpty(dr["Status"].ToString()))
            user.Status = int.Parse(dr["Status"].ToString());

        if (!string.IsNullOrEmpty(dr["IsDel"].ToString()))
            user.IsDel = int.Parse(dr["IsDel"].ToString());

        Session["CurrentEmployee"] = user;
    }

    

#endregion

    public string GetBackUrl()
    {
        if (ViewState["BackUrl"] != null)
        {
            if (ViewState["BackUrl"].ToString() == "")
            {
                ViewState["BackUrl"] = "~/Login.aspx";
            }
            return ViewState["BackUrl"].ToString();
        }
        return ViewState["BackUrl"].ToString();
    }

    public string GetCurrentUrl()
    {
        return ViewState["CurrentUrl"].ToString();
    }
    /// <summary>
    /// 转换int
    /// </summary>
    /// <param name="o"></param>
    /// <returns></returns>
    public int CheckInt(object o)
    {
        if (o != null)
        {
            try
            {
                return int.Parse(o.ToString().Trim());
            }
            catch
            {
                return 0;
            }
        }

        return 0;
    }

    /// <summary>
    /// 转换decimal
    /// </summary>
    /// <param name="o"></param>
    /// <returns></returns>
    public decimal CheckDecimal(object o)
    {
        if (o != null)
        {
            try
            {
                return decimal.Parse(o.ToString().Trim());
            }
            catch
            {
                return 0;
            }
        }

        return 0;
    }

    public string CheckString(object o)
    {
        if (o != null)
        {
            try
            {
                return o.ToString().Trim();
            }
            catch
            {
                return string.Empty;
            }
        }

        return string.Empty;
    }

    #region 验证是否已登陆、防止用户通过URL访问页面息、根据XML生成菜单

    protected virtual void BasePage_Load(object sender, EventArgs e)
    {
        System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("zh-CN", true);
        culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;

        if (Request.QueryString["FromPortal"] + "" == "rlysin" && Request.QueryString["TempUserId"] + "" != "")
        {
            String tempUserId = Decrypt(Request.QueryString["TempUserId"].ToString());//此处放解密接口
            //SignleLoginInfoNoNeedPassword(tempUserId);
        }

        if (string.IsNullOrEmpty(Request.QueryString["TempUserId"]))
        {
            this.IdentifyValidate();
        }

        if (!Page.IsPostBack)
        {
            if (ViewState["BackUrl"] != null && ViewState["BackUrl"] != ViewState["CurrentUrl"])
            {
                ViewState["BackUrl"] = Request.UrlReferrer;
            }
            else
            {
                ViewState["BackUrl"] = "~/Default.aspx";
            }

            ViewState["CurrentUrl"] = HttpContext.Current.Request.Url.PathAndQuery;
        }        
    }

    /// <summary>
    /// 进行DES解密。
    /// </summary>
    /// <param name="pToDecrypt">要解密的以Base64</param>
    /// <param name="sKey">密钥，且必须为8位。</param>
    /// <returns>已解密的字符串。</returns>
    public string Decrypt(string sInputString)
    {
        string sKey = "r1y^@.$~";
        string[] sInput = sInputString.Split("-".ToCharArray());
        byte[] data = new byte[sInput.Length];
        for (int i = 0; i < sInput.Length; i++)
        {
            data[i] = byte.Parse(sInput[i], System.Globalization.NumberStyles.HexNumber);
        }
        System.Security.Cryptography.DESCryptoServiceProvider DES = new System.Security.Cryptography.DESCryptoServiceProvider();
        //DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        System.Security.Cryptography.ICryptoTransform desencrypt = DES.CreateDecryptor();
        byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length); return Encoding.UTF8.GetString(result);
    }

    private void SignleLoginInfoNoNeedPassword(string strLoginName)
    {
        Session["CurrentEmployee"] = null;

        EmployeeAdditional ea = new EmployeeAdditional();
        Pkurg.PWorld.Services.EmployeeAdditionalService eas = new Pkurg.PWorld.Services.EmployeeAdditionalService();
        EmployeeAdditionalQuery eaq = new EmployeeAdditionalQuery();
        eaq.AppendEquals(EmployeeAdditionalColumn.LoginName, strLoginName);
        TList<EmployeeAdditional> eaList = eas.Find(eaq);
        Employee ep = new Employee();
        Pkurg.PWorld.Services.EmployeeService es = new Pkurg.PWorld.Services.EmployeeService();
        if (eaList.Count <= 0)
        {
            //WebCommon.Show(this, "用户名或密码不正确!");
            Response.Redirect("Login.aspx", false);
            return;
        }
        else
        {
            for (int i = 0; i < eaList.Count; i++)
            {
                ep = es.GetByEmployeeCode(eaList[i].EmployeeCode);
                if (ep.Status == 3 && ep.IsDel == 0)
                {
                    break;
                }
            }
        }
        SetLoginModel(ep);
    }

    /// <summary>
    /// 验证是否已登陆、防止用户通过URL访问页面息、根据XML生成菜单
    /// </summary>
    private void ValPage()
    {
        System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("zh-CN", true);
        culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;

        if (string.IsNullOrEmpty(Request.QueryString["TempUserId"]))
        {
            this.IdentifyValidate();
        }

        if (!Page.IsPostBack)
        {
            if (ViewState["BackUrl"] != null && ViewState["BackUrl"] != ViewState["CurrentUrl"])
            {
                ViewState["BackUrl"] = Request.UrlReferrer;
            }
            else
            {
                ViewState["BackUrl"] = "~/Default.aspx";
            }

            ViewState["CurrentUrl"] = HttpContext.Current.Request.Url.PathAndQuery;
        }
    }

    /// <summary>
    /// 判断是否是超级用户
    /// </summary>
    /// <param name="em"></param>
    /// <returns></returns>
    public bool IsSupper(Employee em)
    {
        if (em == null)
        {
            return false;
        }
        string[] Supper = ConfigurationManager.AppSettings["SupperUser"].Split(',');
        for (int i = 0; i < Supper.Length; i++)
        {
            if (Supper[i].ToString() == em.EmployeeCode)
            {
                return true;
            }
        }
        return false;
    }
    /// <summary>
    /// 验证是否已登陆
    /// </summary>
    protected virtual void IdentifyValidate()
    {
        string par = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
        string WebRootPath = HttpContext.Current.Request.ApplicationPath;

        if (CurrentEmployee == null)
        {
            //WebCommon.MsgBox(this.Page, "请重新登录!", ".." + WebRootPath + "/login.aspx");
            //Response.Redirect(System.Configuration.ConfigurationManager.AppSettings["LogoutPage"], false);
            Response.Redirect(System.Configuration.ConfigurationManager.AppSettings["SessionOverduePage"]);
            return;
        }

        ////菜单开关开
        ////超级用户不受限制
        //if (!IsSupper(CurrentEmployee))
        //{
        //    PermissionConfigInfo pc = new PermissionConfigInfo();
        //    if (pc.HavePermission())
        //    {
        //        //防止用户通过URL访问页面息

        //        if (!this.GetUrlPermission(CurrentEmployee.EmployeeCode, par))
        //        {
        //            WebCommon.MsgBox(this.Page, "您没有访问这个页面的权限!", "../../" + WebRootPath + "/login.aspx");
        //        }
        //    }
        //}
        //else
        //{
        //    //解决页面后加ID=GUID后，超级用户无法保存菜单选中状态问题
        //    this.GetSupperUrlPermission(CurrentEmployee.EmployeeCode, par);
        //}
    }

    
  

   
  

    private string ChangeUrl(string path)
    {
        if (!string.IsNullOrEmpty(path))
        {
            string[] urlArr = path.Split('~');
            path = "/Sinopec.RLY.Web.Dev" +  urlArr[1];
        }
        return path;
    }

    /// <summary>
    /// 滚动条定位
    /// </summary>
    /// <param name="DivName">需要定位的Div的ID</param>
    public void RetainScrillPosition(string DivName)
    {
        StringBuilder savep = new StringBuilder();
        StringBuilder setp = new StringBuilder();
        ClientScript.RegisterHiddenField("_scroll" + DivName + "pos", "0");
        savep.Append("<script language='javascript'>");
        savep.Append("function save" + DivName + "ScrollPosition(){");
        savep.Append("if( typeof( document.all." + DivName + " ) != \"undefined\" ){");
        savep.Append("document.forms(0)._scroll" + DivName + "pos.value=document.all." + DivName + ".scrollTop;}");
        savep.Append("}");
        savep.Append("if( typeof( document.all." + DivName + " ) != \"undefined\" ){");
        savep.Append("document.all." + DivName + ".onscroll=save" + DivName + "ScrollPosition;}");
        savep.Append("</script>");
        ClientScript.RegisterStartupScript(this.GetType(), "save" + DivName + "Scroll", savep.ToString());

        if (Page.IsPostBack)
        {
            setp.Append("<script language='javascript'>");
            setp.Append("if( typeof( document.all." + DivName + " ) != \"undefined\" ){");
            setp.Append("document.all." + DivName + ".scrollTop=" + Request["_scroll" + DivName + "pos"] + ";}");
            setp.Append("</script>");
            ClientScript.RegisterStartupScript(this.GetType(), "set" + DivName + "Scroll", setp.ToString());
        }
    }

    #endregion
}
